/**
 option 设置
 {
  leading: true, 开始执行？
    - 注意了只试用执行第一次的时候
  trailing: false 结尾执行？
 }
 */

function throttle(
  fn,
  interval,
  { leading, trailing } = { leading: true, trailing: false }
) {
  let lastTime = 0;
  let timer = null;
  function _throttle() {
    const nowTime = new Date().getTime();

    // leading 处理
    if (!lastTime && !leading) lastTime = nowTime;

    const remainTime = interval - (nowTime - lastTime);
    if (remainTime <= 0) {
      // 之前的timer 没有用处了
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      fn();
      lastTime = nowTime;
      return;
    }

    // 不要重复设置
    if (trailing && !timer) {
      timer = setTimeout(() => {
        timer = null;
        lastTime = !leading ? 0 : new Date().getTime();
        fn();
      }, remainTime);
    }
  }
  return _throttle;
}
